package com.phuong.docbaonhanh;

import java.lang.reflect.Method;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

public class DocBaoNhanh extends Activity {
	
	private WebView mWebView;
	private Button backBtn;
	private Button forwardBtn;
	private Spinner spriner;
	private Dialog aboutDialog;
	private Cursor cursor;
	private DocBaoNhanhDBAdapter dba;
	private String currentUrl = null;
	private ArrayList<String> urls;
	
	protected boolean _active = true;
	protected int _splashTime = 5000; // time to display the splash screen in ms

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		CookieSyncManager.createInstance(DocBaoNhanh.this);
		CookieSyncManager.getInstance().startSync();
		initializeUI();	
		enableZoom();

	}
	
	private class DocBaoViewClient extends WebViewClient
	{
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url)
		{
			view.loadUrl(url);
			return true;
		}
	}

	//used in onCreate() and onConfigurationChanged() to set up the UI elements
	public void initializeUI()
	{
	    //get views from ID's		
		mWebView = (WebView) findViewById(R.id.webview);		
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.setWebViewClient(new DocBaoViewClient());	
		spriner = (Spinner) findViewById(R.id.newsUrl);
		spriner.setFocusable(true);

		ArrayAdapter<CharSequence> websiteNames = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);
		websiteNames.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		dba = new DocBaoNhanhDBAdapter(this);
		dba.open();
		cursor = dba.getAllWebsites();
		urls = new ArrayList<String>();
		//int i = 0;
		while (cursor.moveToNext())
		{
			String results = cursor.getString(1);
			websiteNames.add(results);
			urls.add(cursor.getString(2));
			//i++;
		}		
		spriner.setAdapter(websiteNames);		
		spriner.setOnItemSelectedListener(new MyOnItemSelectedListener());
		if(null !=  currentUrl)
		{
			setSelectItemForWebsiteList(currentUrl);
		}

		backBtn = (Button) findViewById(R.id.backBtn);
		backBtn.setOnClickListener(new MyOnClickListener());

		forwardBtn = (Button) findViewById(R.id.forwardBtn);
		forwardBtn.setOnClickListener(new MyOnClickListener());

	    //etc... hook up click listeners, whatever you need from the Views
	}
	
	//this is called when the screen rotates.
	// (onCreate is no longer called when screen rotates due to manifest, see: android:configChanges)
	@Override
	public void onConfigurationChanged(Configuration newConfig)
	{
	    super.onConfigurationChanged(newConfig);
	    setContentView(R.layout.main);
	    if(null != mWebView.getUrl()){
	    	currentUrl = this.getOriginalUrl(mWebView.getUrl(), false);
	    }
	    
	    initializeUI();
	    enableZoom();
	}
	
	private String getOriginalUrl(String url, boolean isRemoveParameter)
	{
		if(null != url){	
			if(url.indexOf("http://") > -1){
				url = url.substring(7, url.length());//remove http://
			}
			
			if(isRemoveParameter == true){
				url = url.substring(0, url.indexOf("/"));//remove parameter in url
			}
		}
		return url;
	}

	private int getPositionSelectedItem(String url){
		url = this.getOriginalUrl(url, true);
		return urls.indexOf(url);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) 
	{
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			if (mWebView.canGoBack()) {
				mWebView.goBack();				
				setSelectItemForWebsiteList(mWebView.getUrl());
			}
			else {
				DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case DialogInterface.BUTTON_POSITIVE:
							// Yes button clicked
							moveTaskToBack(true);
							//finish();
							break;

						case DialogInterface.BUTTON_NEGATIVE:
							// No button clicked
							// moveTaskToBack(true);
							//finish();
							break;
						}
					}
				};

				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setMessage(R.string.confirm_close)
						.setPositiveButton(R.string.yes, dialogClickListener)
						.setNegativeButton(R.string.no, dialogClickListener)
						.show();
			}

			return true;
		}
		
		/*if(keyCode == KeyEvent.KEYCODE_HOME){
			DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
						// Yes button clicked
						//moveTaskToBack(true);
						finish();
						break;

					case DialogInterface.BUTTON_NEGATIVE:
						// No button clicked
						// moveTaskToBack(true);
						//finish();
						break;
					}
				}
			};

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(R.string.confirm_close)
					.setPositiveButton(R.string.yes, dialogClickListener)
					.setNegativeButton(R.string.no, dialogClickListener)
					.show();
		}*/
		
		return super.onKeyDown(keyCode, event);
	}

	public class MyOnItemSelectedListener implements OnItemSelectedListener 
	{
		public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) 
		{
			String url = "http://";
			if(null != currentUrl && 0 < currentUrl.indexOf("/")){
				url += currentUrl;
				currentUrl = null;
			}else{
				url += urls.get(pos);
			}
			
			mWebView.loadUrl(url);
			enableZoom();
		}

		public void onNothingSelected(AdapterView<?> parent) {
			// Do nothing.
		}
	}
	
	private void setSelectItemForWebsiteList(String url)
	{
		int pos = getPositionSelectedItem(url);
		spriner.setSelection(pos);
		mWebView.loadUrl(url);
	}

	public class MyOnClickListener implements OnClickListener 
	{
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.backBtn:
				if (mWebView.canGoBack()) {
					mWebView.goBack();
					setSelectItemForWebsiteList(mWebView.getUrl());
				}
				break;

			case R.id.forwardBtn:
				if (mWebView.canGoForward()) {
					mWebView.goForward();
					setSelectItemForWebsiteList(mWebView.getUrl());
				}
				break;

			case R.id.closeDialogBtn:
				aboutDialog.cancel();
				break;

			default:
				break;
			}
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.about:
			showAboutDialog();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void showAboutDialog()
	{
		// set up dialog
		aboutDialog = new Dialog(DocBaoNhanh.this);
		aboutDialog.setContentView(R.layout.about_dialog);
		aboutDialog.setTitle(R.string.about);
		aboutDialog.setCancelable(true);

		// set up button
		Button closeAboutBtn = (Button) aboutDialog.findViewById(R.id.closeDialogBtn);
		closeAboutBtn.setOnClickListener(new MyOnClickListener());
		aboutDialog.show();
	}
	
	@Override
	public void onPause()
	{
		super.onPause();
		CookieSyncManager.getInstance().sync();
	}	
	
	@Override
	public void onStop() {
		super.onStop();
		/*dba.close();
		cursor.close();*/
	}	
	
	private void enableZoom(){
		mWebView.getSettings().setBuiltInZoomControls(true);
        try {
            Method m = mWebView.getClass().getMethod("enableMultiTouch", null);
            if (m != null) {
                m.invoke(mWebView, null);
            }
        } catch (Exception e) {
            //e.printStackTrace();
        }

        try {
            Method m = mWebView.getClass().getMethod("enableMultiTouchTextRelow", boolean.class);
            if (m != null) {
                m.invoke(mWebView, false);
            }
        } catch (Exception e) {
            //e.printStackTrace();
        }
        try {

            Method m = mWebView.getClass().getMethod("setIsCacheDrawBitmap", boolean.class);
            if (m != null) {
                m.invoke(mWebView, false);
            }
        } catch (Exception e) {
            // e.printStackTrace();
        }

        // Must for HTC EVO to do text reflow after double tap
        try {
            Method m = mWebView.getClass().getMethod("enableSmartZoom", null);
            if (m != null) {
                m.invoke(mWebView, null);
            }
        } catch (Exception e) {
            // e.printStackTrace();
        }
	}
}